<?php


namespace app\command;


use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Worker;

class HttpProxyCommand extends \Symfony\Component\Console\Command\Command
{

    protected static $defaultName = 'config:http';
    protected static $defaultDescription = 'php-http-proxy服务配置';

    protected function configure()
    {
        $this
            // 命令的名称 ("php console_command" 后面的部分)
            //->setName('model:create')
            // 运行 "php console_command list" 时的简短描述
            ->setDescription('Create new model')
            // 运行命令时使用 "--help" 选项时的完整命令描述
            ->setHelp('This command allow you to create models...')
            // 配置一个参数
            ->addArgument('name', InputArgument::REQUIRED, 'what\'s model you want to create ?');
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        global $argv;
//        $argv[2] = 'start';
        $argv[3] = '-d';
        $output->writeln('php-http-proxy服务启动：');

        // Create a TCP worker.
        $worker = new Worker('tcp://0.0.0.0:8080');
        // 6 processes
        $worker->count = 6;
        // Worker name.
        $worker->name = 'php-http-proxy';
        // Emitted when data received from client.
        $worker->onMessage = function($connection, $buffer)
        {
            // Parse http header.
            list($method, $addr, $http_version) = explode(' ', $buffer);
            $url_data = parse_url($addr);
            $addr = !isset($url_data['port']) ? "{$url_data['host']}:80" : "{$url_data['host']}:{$url_data['port']}";
            // Async TCP connection.
            $remote_connection = new AsyncTcpConnection("tcp://$addr");
            // CONNECT.
            if ($method !== 'CONNECT') {
                $remote_connection->send($buffer);
                // POST GET PUT DELETE etc.
            } else {
                $connection->send("HTTP/1.1 200 Connection Established\r\n\r\n");
            }
            // Pipe.
            $remote_connection ->pipe($connection);
            $connection->pipe($remote_connection);
            $remote_connection->connect();
        };

        Worker::runAll();
        return self::SUCCESS;
    }
}
